<template>
  <div class="ant-card">
    <div class="table-page-search-wrapper">
      <a-form-model
        layout="inline"
        :model="searchForm"
        @submit.prevent="fetch"
        ref="searchForm"
      >
        <a-form-model-item label="用户名：" prop="username">
          <a-input v-model="searchForm.username"></a-input>
        </a-form-model-item>
        <a-form-model-item label="角色：" prop="role.id">
          <a-select v-model="searchForm.role.id" style="width: 120px">
            <a-select-option v-for="d in roleData" :key="d.id"
              >{{ d.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" html-type="submit">查询</a-button>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="default" @click="resetForm('searchForm')"
            >重置
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="table-operator">
      <a-button
        type="primary"
        html-type="submit"
        @click="showModal('新增用户')"
      >
        新增
      </a-button>
    </div>
    <a-modal
      :title="title"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      width="400px"
    >
      <a-form-model
        layout="horizontal"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18, offset: 2 }"
        :model="form"
        @submit.prevent="fetch"
        ref="form"
        :rules="rules"
      >
        <a-form-model-item label="id：" prop="id" v-show="false">
          <a-input v-model="form.id"></a-input>
        </a-form-model-item>
        <a-form-model-item label="用户名：" prop="username">
          <a-input v-model="form.username"></a-input>
        </a-form-model-item>
        <a-form-model-item label="角色：" prop="role.id">
          <a-select v-model="form.role.id" style="width: 120px">
            <a-select-option v-for="d in roleData" :key="d.id"
              >{{ d.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-table
      :dataSource="data"
      rowKey="id"
      bordered
      :pagination="pagination"
      :loading="loading"
    >
      <a-table-column title="id" dataIndex="id" />
      <a-table-column title="用户名" dataIndex="username" />
      <a-table-column title="头像url" dataIndex="userFace" />
      <a-table-column title="角色" dataIndex="role.name" />
      <a-table-column title="操作" key="action">
        <template v-slot="record">
          <a @click.prevent="edit(record.id)">编辑</a>
          <a-divider type="vertical" />
          <a @click.prevent="del(record.id)">删除</a>
        </template>
      </a-table-column>
    </a-table>
  </div>
</template>

<script>
import {
  list,
  getAllRole,
  add,
  getOne,
  del,
  checkUsernameExist
} from "@/api/User";

export default {
  name: "User",
  data() {
    let validateUsernameOnly = (rule, value, callback) => {
      checkUsernameExist(value).then(response => {
        let data = response.data;
        if (data.flag) {
          if (data.data) {
            callback(new Error("用户名已存在"));
          } else {
            callback();
          }
        }
      });
    };
    return {
      //分页
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ["10", "20"], //每页中显示的数据
        showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
      },
      roleData: [], //角色select数据

      //封装查询条件
      searchForm: {
        username: null,
        role: {
          id: null
        }
      },
      loading: false,
      data: [], //table的数据
      title: null, //模态窗口 title
      visible: false, //模态窗口最初隐藏
      //模态窗口的form
      form: {
        id: null,
        username: null,
        role: {
          id: null
        }
      },
      //模态form 校验规则
      rules: {
        username: [
          { required: true, message: "不允许为空", trigger: "blur" },
          { validator: validateUsernameOnly, trigger: "blur" }
        ],
        "role.id": [{ required: true, message: "不允许为空", trigger: "blur" }]
      }
    };
  },
  created() {
    this.fetch();
    this.getAllRole_();
  },
  methods: {
    fetch() {
      this.loading = true;
      console.log("查询条件:", this.searchForm);
      list(
        this.pagination.current,
        this.pagination.pageSize,
        this.searchForm
      ).then(response => {
        let resp = response.data;
        if (resp.flag) {
          this.data = resp.data.results;
          this.pagination.total = resp.data.totalCount;
        }
        this.loading = false;
      });
    },
    getAllRole_() {
      getAllRole().then(response => {
        let resp = response.data;
        if (resp.flag) {
          this.roleData = resp.data;
        }
      });
    },
    //重置查询表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //打开新增模态窗口
    showModal(title) {
      this.title = title;
      this.visible = true;
      //清空上一次输入
      this.$nextTick(() => {
        // this.$nextTick()它是一个异步事件，当渲染结束 之后 ，它的回调函数才会被执行
        // 弹出窗口打开之后 ，需要加载Dom, 就需要花费一点时间，我们就应该等待它加载完dom之后，再进行调用resetFields方法，重置表单和清除样式
        this.$refs["form"].resetFields();
      });
    },
    handleOk() {
      this.$refs.form.validate(valid => {
        if (valid) {
          add(this.form).then(response => {
            let resp = response.data;
            if (resp.flag) {
              this.$message.success("编辑成功");
              //table重新取最新数据
              this.fetch();
              //隐藏dialog
              this.visible = false;
            } else {
              this.$message.error("编辑失败");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleCancel() {
      this.visible = false;
    },
    //修改用户:回显
    edit(id) {
      this.showModal("编辑用户");

      getOne(id).then(response => {
        let resp = response.data;
        if (resp.flag) {
          //给form赋值，必有id
          this.form = resp.data;
        }
      });
    },
    //删除用户
    del(id) {
      this.$confirm({
        title: "提示",
        content: "确定删除吗 ?",
        onOk: () => {
          del(id).then(response => {
            let resp = response.data;
            if (resp.flag) {
              this.fetch();
              this.$message.success("删除成功");
            } else {
              this.$message.error(`删除失败:${resp.message}`);
            }
          });
        },
        onCancel() {}
      });
    }
  }
};
</script>

<style scoped></style>
